package com.sencorsta.ids.core.function;

import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.xml.DOMConfigurator;

import com.sencorsta.ids.core.configure.GlobalConfigure;
import com.sencorsta.ids.core.log.Out;

/**
　　* @description: 功能系统
　　* @author TAO
　　* @date 2019/6/12 17:21
　　*/
public class FunctionSystem {
	/** 操作系统名称 */
	public final static String OS_NAME = System.getProperty("os.name").toUpperCase();

	public static void waitMills(int mills) {
		try {
			Thread.sleep(mills);
		} catch (InterruptedException e) {
			// Out.error(e);
			e.printStackTrace();
		}
	}

	public static void waitSeconds(int second) {
		waitMills(second * GlobalConfigure.TIME_SECOND);
	}

	private static boolean inited = false;

	public static void open() {
		if (inited)
			return;
		inited = true;
//		OsType os = getOSType();
//		if(os != OsType.OS_NT && os != OsType.OS_9X) {
//			RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
//	        String name = runtime.getName();
//	        int pid = Integer.parseInt(name.substring(0, name.indexOf('@')));
//	        File PID = new File(System.getProperty("user.dir") +File.separatorChar+ GConfig.getInstance().get("server.sid")+File.separatorChar + "zone.pid");
//	        if(PID.exists()) {
//	        	System.out.println(System.getProperty("user.dir") +File.separatorChar+ GConfig.getInstance().get("server.sid")+File.separatorChar + "zone.pid");
//	        	System.out.println("This Game is Running? Please stop zone or remove zone.pid!");
//	        	System.exit(1);
//	        } else {
//	        	try {
//	        		PrintWriter output = new PrintWriter(new FileWriter(PID));
//	        		output.write(String.valueOf(pid));
//	        		output.close();
//				} catch (IOException e) {
//					Out.error(e);
//				}
//	        }
//	        PID.deleteOnExit();
//		}

		{
			Out.setting();
			File log4j = new File(GlobalConfigure.DIR_CONF_SERVER + "log4j.xml");
			if (log4j.exists()) {
				DOMConfigurator.configure(log4j.getAbsolutePath());
			}
			// Language.init();
			// GDao.start();
		}

	}

	private static ScheduledExecutorService __EXECUTOR__ = Executors
			.newSingleThreadScheduledExecutor(new PoolFactory("系统维护", true));

	/**
	 *
	 * 功能描述：添加指定执行次数的任务，以毫秒为单位
	 *
	 * @param job
	 * @param delay  初始执行时间
	 * @param period 间隔执行时间
	 * @param count  执行次数
	 * @return
	 */
	public static ScheduledFuture<?> addFixJob(final Runnable job, long delay, final long period, final int count) {
		return __EXECUTOR__.schedule(new Runnable() {
			int total = count;

			@Override
			public void run() {
				try {
					job.run();
				} catch (Exception e) {
					Out.error(e);
				} finally {
					if (--total > 0) {
						addFixJob(job, period, period, total);
					}
				}
			}
		}, delay, TimeUnit.MILLISECONDS);
	}

	/** 添加维护任务(固定延迟) */
	public static ScheduledFuture<?> addFixedRateJob(Runnable runnable, long initialDelay, long period) {
		try {
			return __EXECUTOR__.scheduleAtFixedRate(runnable, Math.max(1L, initialDelay), period,
					TimeUnit.MILLISECONDS);
		} catch (Exception e) {
			Out.error(e);
		}
		return null;
	}

	/** 任务执行结束后再延迟 */
	public static ScheduledFuture<?> addScheduleJob(Runnable runnable, long initialDelay, long delay, TimeUnit unit) {
		try {
			return __EXECUTOR__.scheduleWithFixedDelay(runnable, Math.max(1L, initialDelay), delay, unit);
		} catch (Exception e) {
			Out.error(e);
		}
		return null;
	}

	/** 延迟执行，执行一次 */
	public static ScheduledFuture<?> addDelayJob(Runnable runnable, long delay, TimeUnit unit) {
		return __EXECUTOR__.schedule(runnable, delay, unit);
	}

	public static ScheduledFuture<?> addDelayJob(Runnable runnable, long delay) {
		return __EXECUTOR__.schedule(runnable, delay, TimeUnit.MILLISECONDS);
	}

	public static long getUsedMemoryMB() {
		return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576;
	}

	public static long getFreeMemoryMB() {
		return (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory()
				+ Runtime.getRuntime().freeMemory()) / 1048576;
	}

	public static long getMaxMemoryMB() {
		return Runtime.getRuntime().maxMemory() / 1048576;
	}

}
